import { memo, useEffect, useRef, useState } from "react";
import type { FC } from "react";

// import Form from 'rc-field-form'
import { useSetState } from "ahooks";
import { AutoComplete, Button, Form, Input, Radio, Select, Space } from "antd";
import { DeleteOutlined } from "@ant-design/icons";
import contentStyle from "../../index.module.scss";
import BottomButton from "../../components/bottomButton";
import styles from "./index.module.scss";
import Avator from "./avator";

import { getMonth, getYear } from "@/app/utils";
import { usePersonalDetailsStore, useServerStore, useStore } from "@/store";
import {
  PersonalConst,
  arrivalTime,
  gender,
  politicsStatus,
  workingYears,
} from "@/cvcomponents/common/utils";

interface IndexProps {}

const items = Object.keys(PersonalConst).filter(
  (item) => item !== "name" && item !== "expJob"
) as (keyof PersonalDetails)[];

function PhotoFormItem(props) {
  const { value, onChange } = props;
  const { showPhoto, photo } = value || {};
  return (
    <div style={{ position: "relative", cursor: "pointer" }}>
      <Avator
        photo={photo}
        showPhoto={showPhoto}
        changeShowPhoto={(e: any) => {
          onChange({ ...value, showPhoto: e });
        }}
        photoChange={(url: string) => {
          onChange({ ...value, photo: url });
        }}
      />
      {photo ? (
        <div
          className={styles.editButton}
          style={{
            bottom: "10px",
            top: "auto",
            right: "4px",
            width: "20px",
            height: "20px",
          }}
        >
          <svg
            style={{ width: "14px" }}
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 14 14"
            className="w-4"
          >
            <path
              stroke="currentColor"
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="1.5"
              d="M6.704 1.627H4.523c-1.794 0-2.919 1.27-2.919 3.068v4.85c0 1.797 1.12 3.067 2.919 3.067H9.67c1.8 0 2.92-1.27 2.92-3.068v-2.35"
            ></path>
            <path
              stroke="currentColor"
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="1.5"
              d="M5.15 6.37l4.36-4.359a1.391 1.391 0 011.966 0l.71.71a1.39 1.39 0 010 1.967l-4.38 4.38c-.238.237-.56.37-.896.37H4.725l.054-2.204c.009-.324.141-.634.37-.864z"
              clipRule="evenodd"
            ></path>
            <path
              stroke="currentColor"
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="1.5"
              d="M8.847 2.685l2.663 2.663"
            ></path>
          </svg>
        </div>
      ) : null}
    </div>
  );
}

const Index: FC<IndexProps> = () => {
  const { updateDetail, personalDetails, updateDetailOrder } =
    usePersonalDetailsStore();
  const { setCurrentTab } = useStore();
  const oldPersonalDetails = useRef(null);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const [state, setState] = useSetState<{
    months: any[];
    years: any[];
    displayItems: (keyof PersonalDetails)[];
    canSelectedItems: (keyof PersonalDetails)[];
  }>({
    months: [],
    years: [],
    displayItems: [],
    canSelectedItems: [],
  });
  const serverStore = useServerStore();
  useEffect(() => {
    oldPersonalDetails.current = {
      ...personalDetails,
      detailsOrder: [...(personalDetails.detailsOrder || [])],
    };
    form.setFieldsValue({
      ...personalDetails,
      birthDay: personalDetails.birthDay || {
        year: undefined,
        month: undefined,
      },
    });
    setState({ months: getMonth(12), years: getYear(80) });
  }, []);
  useEffect(() => {
    const map = personalDetails.detailsOrder?.reduce((o, n) => {
      o.add(n);
      return o;
    }, new Set(["name", "expJob"]));
    setState({
      displayItems: items.filter((v) => map?.has(v)),
      canSelectedItems: items.filter((v) => !map?.has(v)),
    });
  }, [personalDetails]);
  const onRemove = (key: any) => {
    const detailsOrder = personalDetails.detailsOrder || [];
    const index = detailsOrder?.findIndex((d) => d === key);
    let deleted: any = "";
    if (index != null && index !== -1) {
      [deleted] = detailsOrder?.splice(index, 1);
    }

    const obj = { ...personalDetails, detailsOrder };
    if (deleted === "birthDay") {
      obj.showAge = false;
    }
    obj[deleted] = "";
    form.setFieldValue(deleted, "");
    updateDetail(obj);
  };
  const onChangeCurrent = () => {
    setCurrentTab("content");
  };
  const reset = () => {
    updateDetail({ ...oldPersonalDetails.current });
  };
  return (
    <div className={styles.personalDetailEdit}>
      <div className={contentStyle.card} style={{ overflow: "hidden" }}>
        <Form
          layout="vertical"
          form={form}
          onValuesChange={(value, values) => {
            const formDetail = { ...personalDetails };

            if (value.birthDay) {
              updateDetail({ ...formDetail, birthDay: values.birthDay });
            } else if (value.weightHeight) {
              updateDetail({
                ...formDetail,
                weightHeight: values.weightHeight,
              });
            } else {
              updateDetail({ ...formDetail, ...value });
            }
          }}
        >
          {/* <Form.Item name={'photoObj'} style={{ marginTop: '10px', display: 'flex', justifyContent: 'center' }}>
          <PhotoFormItem />
        </Form.Item> */}
          <div
            style={{
              margin: "10px 10px 20px",
              fontWeight: "bold",
              fontSize: "16px",
            }}
          >
            个人信息
          </div>
          <div style={{ display: "flex", gap: "20px" }}>
            <div style={{ flex: 1 }}>
              <Form.Item
                name={"name"}
                label={"姓　　名"}
                rules={[{ required: true, message: "姓名必填" }]}
              >
                <Input allowClear></Input>
              </Form.Item>
              <Form.Item name={"expJob"} label={"求职岗位"}>
                <Input allowClear></Input>
              </Form.Item>
            </div>
            <Form.Item
              name={"photoObj"}
              style={{
                marginTop: "10px",
                display: "flex",
                justifyContent: "center",
              }}
            >
              <PhotoFormItem />
            </Form.Item>
          </div>
          {state.displayItems?.map((key) => {
            if (key === "workingYears") {
              return (
                <Form.Item key={key} label="工作年限">
                  <Space.Compact block>
                    <Form.Item name={"workingYears"} noStyle>
                      <AutoComplete
                        allowClear
                        options={workingYears}
                        style={{ width: "100%" }}
                      />
                    </Form.Item>
                    <Button
                      icon={<DeleteOutlined style={{ color: "red" }} />}
                      onClick={() => {
                        onRemove(key);
                      }}
                    ></Button>
                  </Space.Compact>
                </Form.Item>
              );
            }
            if (key === "politicsStatus") {
              return (
                <Form.Item key={key} label="政治面貌">
                  <Space.Compact block>
                    <Form.Item name={"politicsStatus"} noStyle>
                      <AutoComplete
                        allowClear
                        options={politicsStatus}
                        style={{ width: "100%" }}
                      />
                    </Form.Item>
                    <Button
                      icon={<DeleteOutlined style={{ color: "red" }} />}
                      onClick={() => {
                        onRemove(key);
                      }}
                    ></Button>
                  </Space.Compact>
                </Form.Item>
              );
            }
            if (key === "birthDay") {
              return (
                <div key={key}>
                  <Form.Item key={key} label="出生日期">
                    <Space.Compact block>
                      <Space.Compact block>
                        <Form.Item name={["birthDay", "year"]} noStyle>
                          <Select allowClear options={state.years}></Select>
                        </Form.Item>
                        <Form.Item name={["birthDay", "month"]} noStyle>
                          <Select allowClear options={state.months}></Select>
                        </Form.Item>
                      </Space.Compact>
                      <Button
                        icon={<DeleteOutlined style={{ color: "red" }} />}
                        onClick={() => {
                          onRemove(key);
                        }}
                      ></Button>
                    </Space.Compact>
                  </Form.Item>
                  <div style={{ overflow: "hidden" }}>
                    <Form.Item
                      name={"showAge"}
                      style={{
                        float: "right",
                        marginRight: "30px",
                        marginTop: "10px",
                      }}
                    >
                      <Radio.Group>
                        <Radio value={false}>生日</Radio>
                        <Radio value={true}>年龄</Radio>
                      </Radio.Group>
                    </Form.Item>
                  </div>
                </div>
              );
            }
            if (key === "gender") {
              return (
                <Form.Item key={key} label="性 别">
                  <Space.Compact block>
                    <Form.Item name={"gender"} noStyle>
                      <Select allowClear options={gender}></Select>
                    </Form.Item>
                    <Button
                      icon={<DeleteOutlined style={{ color: "red" }} />}
                      onClick={() => {
                        onRemove(key);
                      }}
                    ></Button>
                  </Space.Compact>
                </Form.Item>
              );
            }
            if (key === "weightHeight") {
              return (
                <Form.Item key={key} label="身高/体重">
                  <Space.Compact block>
                    <Space.Compact block>
                      <Form.Item name={["weightHeight", "height"]} noStyle>
                        <Input
                          allowClear
                          addonAfter={<div style={{ width: "25px" }}>cm</div>}
                        ></Input>
                      </Form.Item>
                      <Form.Item name={["weightHeight", "weight"]} noStyle>
                        <Input
                          allowClear
                          addonAfter={<div style={{ width: "25px" }}>kg</div>}
                        ></Input>
                      </Form.Item>
                    </Space.Compact>
                    <Button
                      icon={<DeleteOutlined style={{ color: "red" }} />}
                      onClick={() => {
                        onRemove(key);
                      }}
                    ></Button>
                  </Space.Compact>
                </Form.Item>
              );
            }
            if (key === "arrivalTime") {
              return (
                <Form.Item key={key} label={PersonalConst[key]}>
                  <Space.Compact block>
                    <Form.Item name={key} noStyle>
                      <AutoComplete
                        allowClear
                        options={arrivalTime}
                        style={{ width: "100%" }}
                      />
                    </Form.Item>
                    <Button
                      icon={<DeleteOutlined style={{ color: "red" }} />}
                      onClick={() => {
                        onRemove(key);
                      }}
                    ></Button>
                  </Space.Compact>
                </Form.Item>
              );
            }
            return (
              <Form.Item
                key={key}
                label={PersonalConst[key]}
                required={key === "name"}
              >
                <Space.Compact block>
                  <Form.Item
                    name={key}
                    rules={
                      key === "name"
                        ? [{ required: true, message: "姓名必填" }]
                        : []
                    }
                    noStyle
                  >
                    <Input allowClear></Input>
                  </Form.Item>
                  {key !== "name" &&
                  key !== "email" &&
                  key !== "phoneNumber" &&
                  key !== "expJob" ? (
                    <Button
                      icon={<DeleteOutlined style={{ color: "red" }} />}
                      onClick={() => {
                        onRemove(key);
                      }}
                    ></Button>
                  ) : null}
                </Space.Compact>
              </Form.Item>
            );
          })}

          <Form.Item name={"id"} hidden>
            <Input allowClear></Input>
          </Form.Item>
        </Form>
        <div className={styles.infoWraper}>
          {state.canSelectedItems.map((item) => {
            return (
              <div
                className={styles.item}
                key={item}
                onClick={() => {
                  const detailsOrder = personalDetails.detailsOrder || [];
                  detailsOrder?.push(item);
                  updateDetailOrder(detailsOrder);
                }}
              >
                <svg
                  style={{ width: "15px", marginRight: "4px" }}
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 19 19"
                  fill="currentColor"
                  className="w-[1.4em]"
                >
                  <path
                    fillRule="evenodd"
                    d="M10.8 2.452a1.3 1.3 0 10-2.6 0v5.316H2.885a1.3 1.3 0 000 2.6H8.2v5.315a1.3 1.3 0 002.6 0v-5.315h5.315a1.3 1.3 0 100-2.6H10.8V2.452z"
                    clipRule="evenodd"
                  ></path>
                </svg>
                {PersonalConst[item]}
              </div>
            );
          })}
        </div>
      </div>
      <BottomButton
        loading={loading}
        onCancel={() => {
          onChangeCurrent?.();
          reset();
        }}
        onConfirm={async () => {
          // const formData = await form.validateFields()
          // let res
          // try {
          //   if (personalDetails.id) {
          //     setLoading(true)
          //     res = await serverStore.updatePersonalDetail(personalDetails)
          //     setLoading(false)
          //   }
          //   else {
          //     setLoading(true)
          //     res = await serverStore.saveAll()
          //     setLoading(false)
          //   }
          // }
          // catch {
          //   setLoading(false)
          // }
          onChangeCurrent?.();
          // updatePersonalDetail({})
        }}
      />
    </div>
  );
};

export default memo(Index);
